struct ListNode {
    int val;
    ListNode* next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode* next) : val(x), next(next) {}
};

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* r = head;
        while (n-- > 1) {
            r = r->next;
        }
        ListNode* l = head;
        ListNode* pre = nullptr;
        while (r->next != nullptr) {
            r = r->next;
            pre = l;
            l = l->next;
        }
        if (pre == nullptr) {
            head = head->next;
        }
        else {
            pre->next = l->next;
        }
        return head;
    }
};